<?php

/**
 * Database interface for the eMedia plugin
 *
 * @copyright (c) 2012 University of Geneva
 * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
 * @author Laurent Opprecht laurent@opprecht.info
 */
class EMediaStore
{

    const TABLE = 'emedia';

    public static function select_by_id($id)
    {
        global $DB;
        $result = $DB->get_record(self::TABLE, array('id' => $id), '*', MUST_EXIST);
        $result = self::process($result);
        return $result;
    }

    public static function select_by_cm($cm)
    {
        return self::select_by_id($cm->instance);
    }

    public static function select_by_course($course)
    {
        $result = array();
        $items = get_all_instances_in_course('emedia', $course);
        foreach ($items as $item) {
            $result[] = self::process($item);
        }
        return $result;
    }

    /**
     * Deserialize data
     * @param type $data 
     */
    protected static function process($data)
    {
        $result = $data;
        $result->options = empty($result->options) ? array() : unserialize($result->options);
        $result->data = empty($result->data) ? array() : unserialize($result->data);
        if ($result->intro) {
            $result->description = $result->intro;
        } else {
            $result->description = isset($result->data['description']) ? $result->data['description'] : '';
        }
        $result->title = $result->name ? $result->name : $result->data['title'];

        return $result;
    }

}